const { response } = require('express');
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient
var config = require('../config/db')
var passport = require('passport');
var mongdb = require('mongodb')
var mongodb = require('mongodb')


/* 获取用户订单信息 */
router.get('/getOrdersByUserId', function (req, res, next) {
  //1.接受请求的用户编号参数
  var userId = parseInt(req.query.userId)
  //2.连接数据库
  MongoClient.connect(config.url, function (err, client) {
    if (err) {
      console.log('数据库连接失败', err)
      res.json({ code: 200, message: 'error', data: err })
    } else {
      //3.获取用户的所有订单
      var db = client.db()
      db.collection('orderTest').aggregate([
        {
          $lookup:
          {
            from: "order_detail",
            localField: "order_id",
            foreignField: "order_id",
            as: "order_detail"
          }
        },
        {
          $match: { user_id: userId }
        }
      ]).toArray(function (err, result) {
        if (err) {
          console.log('数据获取失败！', err)
        } else {
          res.json({ code: 200, message: 'ok', data: result })
          client.close()
        }
      })
    }
  })
});


/*显示订单数据 */
router.get('/getOrders', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  let orders = await db.collection('orderTest').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
  if (orders.length >= 0) {
    res.json({ code: 200, message: 'ok ', data: orders });
  }
  else {
    res.json({ code: 200, message: 'error' });
  }
});



/*添加订单 */
router.post('/addOrder', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取需要添加的订单商品信息
  let order = req.body.order
  console.log('myorder: ', order);
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  //创建订单对象
  let newOrder = {
    "userId": req.user._id,
    "products": order.products,
    "totalPrice": order.totalPrice,
    "address": order.checkAddress,
    "addTime": new Date().toLocaleString(),
    "state": 1,      //1-待支付，2-已支付，3-已评价
    "comment": ''
  }
  //执行添加订单的操作
  let results = await db.collection('orderTest').insertOne(newOrder)
  let bookType = newOrder.products[0].type
  let likeList = ['temp', '小说', '艺术', '历史', '法律', '心理', '儿童文学', '动漫绘本',
    '启蒙益智', '技能培养', '中小教辅', '字典词典', '时尚娱乐', '养生保健', '管理', '经济']
  let newLike = 6
  for (let i = 0; i < likeList.length; i++) {
    if (likeList[i] == bookType) {
      newLike = i 
    }
  }
  await db.collection('user').updateOne({ '_id': new mongodb.ObjectId(req.user._id) }, { $set: { user_like: newLike } })
  //判断是否添加成功
  if (results.acknowledged) {
    let orders = await db.collection('orderTest').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
    console.log('orders', orders[0]._id)
    res.json({ code: 200, message: newLike, data: orders[0]._id });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});

/*支付，确认和评论，并修改订单状态*/
router.put('/editOrder', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取需要修改的订单商品信息
  let orderId = req.body.params.orderId
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let state = req.body.params.state
  let db = client.db()
  console.log(' req.body.params', req.body.params);
  let results = await db.collection('orderTest').updateOne({ _id: new mongdb.ObjectId(orderId) }, { $set: { state } })
  //判断是否修改成功
  if (results.acknowledged) {
    console.log('editOrderresults: ', results)
    res.json({ code: 200, message: 'ok' });
  } else {
    res.json({ code: 280, message: 'error' });
  }
});


/*删除*/
router.delete('/delOrders', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  // 获取需要删除的id
  let id = req.query.id
  console.log('id =', id)
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  //执行删除的操作
  let results = await db.collection('orderTest').deleteOne({ _id: new mongdb.ObjectId(id) })
  console.log('results:', results)
  //判断是否删除成功
  if (results.acknowledged) {
    res.json({
      code: 200, message: 'ok'
    });
  } else {
    res.json({
      code: 200, message: 'error'
    });
  }
});

/*添加订单的评价内*/
router.put('/addOrderComment', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取需要修改的订单商品信息
  let orderId = req.body.params.orderId
  let content = req.body.params.comment
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  let comment = {}
  comment.content = content
  comment.commentTime = new Date()
  //执行添加订单的的操作
  let results = await db.collection('orderTest').updateOne({ _id: new mongdb.ObjectId(orderId) }, { $set: { comment } })
  //判断是否修改成功
  if (results.acknowledged) {
    console.log('results: ', results)
    res.json({ code: 200, message: 'ok ' });
  }
  else {
    res.json({ code: 20, message: 'error' });
  }
});


/*获取当前用户的所有订单评价信息*/
router.get('/getOrdersComment', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  let orders = await db.collection('orderTest').find({ userId: req.user._id, comment: { $ne: null } }).sort({ 'addTime': -1 }).toArray()
  if (orders.length >= 0) {
    res.json({ code: 200, message: 'ok ', data: orders });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});



/* 修改订单状态 */
// router.get('/updOrdersStatus', function (req, res, next) {
//   res.send('修改订单状态');
// });

module.exports = router;